package cn.leaf.calculator.old;

import lombok.Getter;
import lombok.Setter;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 计算公式
 *
 * @author 李克国
 * @version 1.0.0

 */
public class CalFormula {

    /**
     * 匹配#{#value} 形式的参数
     */
    private final String PARAM = "(?<=#\\{#)(.+?)(?=\\})";
    @Getter
    private String formula;
    @Getter
    @Setter
    private String formulaName;

    private List<Serializable> params;

    public CalFormula(String formula) {
        this.formula = formula;
    }

    public void setFormula(String formula) {
        this.formula = formula;
        this.params = null;
    }

    /**
     * 获取参数
     *
     * @return {@link Serializable} list
     * @description 懒加载执行解析
     */
    public List<Serializable> getParams() {
        if (params == null) {
            params = analyticParams();
        }
        return params;
    }

    /**
     * 解析 参数
     *
     * @return list
     */
    private List<Serializable> analyticParams() {
        Assert.notNull(formula, "公式不能为空");
        List<Serializable> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(PARAM);
        Matcher matcher = pattern.matcher(formula);
        while (matcher.find()) {
            result.add(matcher.group());

        }
        return result;
    }

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {

    }

    /**
     * 合法性
     *
     * @return boolean
     */
    private boolean valid() {
        return false;
    }


}
